#include <p18f452.h>
#include <stdlib.h>
#include <adc.h>
#include <timers.h>

#pragma	config	OSC = XT,	OSCS = OFF
#pragma	config	PWRT = ON,	BOR = ON,	BORV = 25
#pragma 	config	WDT = OFF,	WDTPS = 128
#pragma	config	CCP2MUX = OFF,	LVP = OFF//programacion bajo voltaje
#pragma	config	STVR = ON//stack overflow
#pragma	config	WRT0 =OFF,	WRT1 = OFF,	WRT2 = OFF
#pragma	config	WRT3 = OFF,	WRTB = OFF
#pragma	config	EBTR0 = OFF,	EBTR1 = OFF,	EBTR2 = OFF
#pragma	config	EBTR3 = OFF,	EBTRB = OFF

unsigned char bobinas1[4]={0b00000001,0b00000010,0b00000100,0b00001000};
unsigned char bobinas2[4]={0b00001000,0b00000100,0b00000010,0b00000001};
int i;
unsigned int dato;
unsigned int adc(unsigned char canal);
void retardo(unsigned int);

void main (void)
{
    TRISA=1;
    PORTA=0;
    TRISD=0b11110000;
    PORTD=0;
    LATD=0;
    OpenADC(ADC_FOSC_8 & ADC_RIGHT_JUST & ADC_1ANA_0REF,ADC_INT_OFF);
    while(1)
    {
        if(PORTDbits.RD4==1)
        {
            dato=adc(ADC_CH0);
            if(PORTDbits.RD5==1)
            {
                for(i=0;i<4;i++)
                {
                    retardo(dato);
                    LATD=bobinas1[i];
                }
            }
            if(PORTDbits.RD5==0)
            {
                for(i=0;i<4;i++)
                {
                    retardo(dato);
                    LATD=bobinas2[i];
                } 
            }
        }   
    }
}

unsigned int adc(unsigned char canal)
{
    unsigned int result;
    SetChanADC(canal);
    ConvertADC();
    while(BusyADC());
    result=ReadADC();
    return result;
}

void retardo(unsigned int dato)
{
    int j;
    dato=(dato/30)+5;
    for(j=0;j<dato;j++)
    {
        Delay1KTCYx(5);
    }
}